import { ref, onMounted, toRaw } from 'vue'
import localforage from 'localforage'

localforage.config({
    driver: [localforage.INDEXEDDB, localforage.LOCALSTORAGE],
    name: 'deepchat',
    storeName: 'chat_store'
})

export function useChatStore() {
    const chatList = ref([])

    // 初始化加载
    onMounted(async () => {
        const storedChats = await localforage.getItem('chatList')
        if (storedChats) chatList.value = storedChats
    })

    const getChatList = () => chatList.value

    const addChatList = async (friendInfo) => {
        const index = chatList.value.findIndex(chat => chat.id == friendInfo.id)

        const list = toRaw(chatList.value)
        const newList = [...list] 

        if (index > -1) {
            // 如果已存在，先移除
            newList.splice(index, 1)
        } 

        //加入到数组的第一项
        const itemInfo = toRaw(friendInfo)
        newList.unshift(itemInfo)

        chatList.value = newList

        // 存储前移除响应式
        await localforage.setItem('chatList', toRaw(chatList.value))
    }

    const clearChatList = async (friendId) => {
        chatList.value = chatList.value.filter(item => item.friendId !== friendId)
        await localforage.setItem('chatList', toRaw(chatList.value))
    }

    return { chatList, getChatList, addChatList, clearChatList }
}